<template>
  <div class="check-apply-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>开具检查申请</span>
        </div>
      </template>

      <!-- 患者基本信息 -->
      <el-form :model="form" label-width="120px" :inline="true">
        <el-form-item label="病历号">
          <el-input v-model="form.caseNumber" disabled />
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="form.patientName" disabled />
        </el-form-item>
        <el-form-item label="患者性别">
          <el-input v-model="form.gender" disabled />
        </el-form-item>
        <el-form-item label="患者年龄">
          <el-input v-model="form.age" disabled />
        </el-form-item>
      </el-form>

      <!-- 检查项目搜索和选择 -->
      <el-divider content-position="left">检查项目</el-divider>
      <div class="search-bar">
        <el-select v-model="searchParams.recordType" multiple placeholder="请选择检查类型" style="width: 300px">
          <el-option label="检查" :value="1" />
          <el-option label="治疗" :value="2" />
          <el-option label="材料" :value="3" />
        </el-select>
        <el-input
          v-model="searchParams.keyword"
          placeholder="请输入项目名称、编码或拼音码"
          style="width: 300px; margin-left: 10px"
          clearable
          @clear="handleSearchClear"
        />
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px" :loading="loading">搜索</el-button>
      </div>

      <!-- 检查项目表格 -->
      <el-table
        :data="fmedItems"
        border
        style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemCode" label="项目编码" width="120" />
        <el-table-column prop="itemName" label="项目名称" width="180" />
        <el-table-column prop="format" label="规格" width="120" />
        <el-table-column prop="price" label="单价(元)" width="100" align="right">
          <template #default="{row}">
            {{ row.price ? row.price.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="执行科室" width="150" />
        <el-table-column label="操作" width="80">
          <template #default="{row}">
            <el-button link type="primary" @click="handleAddItem(row)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 已选检查项目 -->
      <el-divider content-position="left">已选项目</el-divider>
      <el-table :data="selectedItems" border style="width: 100%">
        <el-table-column prop="itemName" label="项目名称" width="180" />
        <el-table-column prop="price" label="单价(元)" width="100" align="right">
          <template #default="{row}">
            {{ row.price ? row.price.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100">
          <template #default="{row, $index}">
            <el-input-number v-model="row.num" :min="1" :max="10" @change="handleNumChange($index)" />
          </template>
        </el-table-column>
        <el-table-column label="是否加急" width="120">
          <template #default="{row, $index}">
            <el-switch
              v-model="row.isUrgent"
              :active-value="1"
              :inactive-value="0"
              active-text="加急"
              inactive-text="普通"
              @change="handleUrgentChange($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="检查部位" width="200">
          <template #default="{row, $index}">
            <el-input v-model="row.position" placeholder="请输入检查部位" />
          </template>
        </el-table-column>
        <el-table-column label="目的要求">
          <template #default="{row, $index}">
            <el-input v-model="row.objective" placeholder="请输入检查目的要求" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{row, $index}">
            <el-button link type="danger" @click="handleRemoveItem($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 费用汇总 -->
      <div class="fee-summary">
        <div class="fee-item">
          <span>项目费用：</span>
          <span class="fee-value">¥{{ totalItemFee.toFixed(2) }}</span>
        </div>
        <div class="fee-item">
          <span>加急费用：</span>
          <span class="fee-value">¥{{ urgentFee.toFixed(2) }}</span>
        </div>
        <div class="fee-item total">
          <span>总费用：</span>
          <span class="fee-value">¥{{ totalFee.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div style="margin-top: 20px; text-align: right">
        <el-button type="primary" @click="showPaymentDialog" :disabled="selectedItems.length === 0 || !canSubmit">
          支付并提交申请
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </el-card>

    <!-- 支付弹窗 -->
    <el-dialog v-model="paymentDialogVisible" title="支付检查费用" width="30%">
      <div class="payment-content">
        <div class="payment-info">
          <p><strong>患者姓名：</strong>{{ form.patientName }}</p>
          <p><strong>病历号：</strong>{{ form.caseNumber }}</p>
          <p><strong>项目费用：</strong>¥{{ totalItemFee.toFixed(2) }}</p>
          <p><strong>加急费用：</strong>¥{{ urgentFee.toFixed(2) }}</p>
          <p><strong>总费用：</strong>¥{{ totalFee.toFixed(2) }}</p>
        </div>
        <div class="payment-methods">
          <h4>选择支付方式：</h4>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="cash">现金支付</el-radio>
            <el-radio label="medicalInsurance">医保支付</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="paymentLoading">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const apiRequest = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiRequest.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiRequest.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('响应拦截器错误:', error)
    if (error.response) {
      console.error('错误状态:', error.response.status)
      console.error('错误数据:', error.response.data)
      let errorMessage = '请求失败'
      if (error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message
      } else if (error.response.status === 400) {
        errorMessage = '请求参数错误，请检查输入'
      } else if (error.response.status === 401) {
        errorMessage = '未授权，请重新登录'
      } else if (error.response.status === 500) {
        errorMessage = '服务器内部错误'
      }
      ElMessage.error(errorMessage)
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接')
    } else {
      ElMessage.error('请求配置错误')
    }
    return Promise.reject(error)
  }
)

// 表单数据
const form = ref({
  caseNumber: '',
  patientName: '',
  gender: '',
  age: '',
  medicalRecordId: null,
  registerId: null
})

// 搜索参数
const searchParams = ref({
  recordType: [1, 2, 3], // 默认选择所有类型
  keyword: ''
})

// 检查项目列表
const fmedItems = ref([])
// 已选项目列表
const selectedItems = ref([])
// 加载状态
const loading = ref(false)

// 支付相关状态
const paymentDialogVisible = ref(false)
const paymentMethod = ref('wechat')
const paymentLoading = ref(false)

// 从localStorage中获取用户信息
const userInfo = computed(() => {
  try {
    const info = localStorage.getItem('userInfo')
    return info ? JSON.parse(info) : null
  } catch (e) {
    console.error('解析用户信息失败:', e)
    return null
  }
})

// 计算属性
const totalItemFee = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + (item.price * item.num), 0)
})

const urgentFee = computed(() => {
  return selectedItems.value
    .filter(item => item.isUrgent === 1)
    .reduce((sum, item) => sum + (item.price * item.num * 0.2), 0) // 加急费为项目费用的20%
})

const totalFee = computed(() => {
  return totalItemFee.value + urgentFee.value
})

const canSubmit = computed(() => {
  return selectedItems.value.length > 0 && 
         selectedItems.value.every(item => item.position && item.objective)
})

// 初始化数据
onMounted(() => {
  const patientInfo = JSON.parse(sessionStorage.getItem('currentPatient')) || {}
  if (patientInfo && patientInfo.caseNumber) {
    form.value = {
      ...form.value,
      caseNumber: patientInfo.caseNumber,
      patientName: patientInfo.realName,
      gender: patientInfo.gender === 1 ? '男' : '女',
      age: `${patientInfo.age}${patientInfo.ageType || '岁'}`,
      medicalRecordId: patientInfo.medicalRecordId,
      registerId: patientInfo.registerId
    }
    loadFmedItems()
  } else {
    ElMessage.warning('未找到患者信息，请先进行病案首页登记')
  }
  
  // 检查用户登录状态
  checkLoginStatus()
})

// 检查登录状态
const checkLoginStatus = () => {
  if (!userInfo.value || !userInfo.value.id) {
    ElMessage.warning('请先登录')
  }
}

// 加载检查项目
const loadFmedItems = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      recordTypes: searchParams.value.recordType.join(','),
      keyword: searchParams.value.keyword || ''
    }

    const response = await apiRequest.get('/checkApply/getFmeditems', { params })
    
    if (response && Array.isArray(response)) {
      fmedItems.value = response.map(item => ({
        ...item,
        itemCode: item.itemCode || item.itemcode || '',
        itemName: item.itemName || item.itemname || '',
        deptName: item.deptName || '未知科室'
      }))
    } else {
      fmedItems.value = []
      ElMessage.warning('未获取到检查项目数据')
    }
  } catch (error) {
    console.error('加载检查项目失败:', error)
    fmedItems.value = []
  } finally {
    loading.value = false
  }
}

// 搜索检查项目
const handleSearch = () => {
  if (searchParams.value.recordType.length === 0) {
    ElMessage.warning('请至少选择一种检查类型')
    return
  }
  loadFmedItems()
}

// 清除搜索
const handleSearchClear = () => {
  searchParams.value.keyword = ''
  loadFmedItems()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  const newItems = selection.filter(item => 
    !selectedItems.value.some(selected => selected.itemId === item.id)
  )
  
  newItems.forEach(item => {
    selectedItems.value.push({
      itemId: item.id,
      itemName: item.itemName || item.itemname,
      price: item.price,
      num: 1,
      isUrgent: 0,
      position: '',
      objective: '',
      deptId: item.deptId,
      recordType: item.recordType
    })
  })
}

// 手动添加项目
const handleAddItem = (item) => {
  if (!selectedItems.value.some(selected => selected.itemId === item.id)) {
    selectedItems.value.push({
      itemId: item.id,
      itemName: item.itemName || item.itemname,
      price: item.price,
      num: 1,
      isUrgent: 0,
      position: '',
      objective: '',
      deptId: item.deptId,
      recordType: item.recordType
    })
    ElMessage.success('已添加检查项目')
  } else {
    ElMessage.warning('该项目已添加')
  }
}

// 移除项目
const handleRemoveItem = (index) => {
  selectedItems.value.splice(index, 1)
}

// 数量变化处理
const handleNumChange = (index) => {
  // 可以添加数量变化的逻辑
}

// 加急状态变化处理
const handleUrgentChange = (index) => {
  // 可以添加加急状态变化的逻辑
}

// 显示支付对话框
const showPaymentDialog = () => {
  // 验证所有已选项目的必填字段
  const invalidItem = selectedItems.value.find(item => !item.position || !item.objective)
  if (invalidItem) {
    ElMessage.warning('请完善所有检查项目的检查部位和目的要求')
    return
  }
  
  paymentDialogVisible.value = true
}

// 确认支付
const confirmPayment = async () => {
  paymentLoading.value = true
  try {
    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 支付成功后提交申请
    await handleSubmit()
    
    // 关闭支付对话框
    paymentDialogVisible.value = false
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败: ' + (error.message || '未知错误'))
  } finally {
    paymentLoading.value = false
  }
}

// 提交申请
const handleSubmit = async () => {
  try {
    // 确保基本参数存在
    if (!form.value.medicalRecordId || !form.value.registerId) {
      ElMessage.error('患者信息不完整，请重新选择患者')
      console.error('提交失败：缺少medicalRecordId或registerId', form.value)
      return
    }
    
    // 确保已选择项目
    if (selectedItems.value.length === 0) {
      ElMessage.warning('请至少选择一个检查项目')
      return
    }
    
    // 验证所有已选项目的必填字段
    const invalidItem = selectedItems.value.find(item => !item.position || !item.objective)
    if (invalidItem) {
      ElMessage.warning('请完善所有检查项目的检查部位和目的要求')
      return
    }
    
    // 获取医生ID
    const doctorId = userInfo.value?.id || localStorage.getItem('userId')
    
    if (!doctorId) {
      // 尝试从服务器获取用户信息
      const userData = await fetchUserInfo()
      if (userData && userData.id) {
        // 保存用户信息到localStorage
        localStorage.setItem('userInfo', JSON.stringify(userData))
        // 继续提交
        await submitCheckApply(userData.id)
      } else {
        throw new Error('未获取到医生信息，请重新登录')
      }
    } else {
      // 继续提交
      await submitCheckApply(parseInt(doctorId))
    }
  } catch (error) {
    console.error('提交失败详情:', error)
    if (error.message && error.message !== 'cancel') {
      ElMessage.error(error.message)
    }
  }
}

// 从服务器获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await apiRequest.get('/api/user/info')
    if (response && response.id) {
      return response
    }
    return null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 提交检查申请
const submitCheckApply = async (doctorId) => {
  // 准备提交数据
  const submitData = {
    medicalRecordId: form.value.medicalRecordId,
    registerId: form.value.registerId,
    doctorId,
    itemIds: selectedItems.value.map(item => item.itemId).join(','),
    objectives: selectedItems.value.map(item => item.objective).join(','),
    positions: selectedItems.value.map(item => item.position).join(','),
    isUrgents: selectedItems.value.map(item => item.isUrgent).join(','),
    nums: selectedItems.value.map(item => item.num).join(','),
    paymentMethod: paymentMethod.value,
    paymentAmount: totalFee.value
  }

  console.log('最终提交数据:', submitData)

  // 发送请求 - 修改为使用params方式传递参数，匹配后端@RequestParam注解
  const response = await apiRequest.post('/checkApply/createCheckApply', null, {
    params: submitData
  })

  // 处理响应
  if (response === true || (response && response.success)) {
    ElMessage.success('检查申请提交成功')
    handleReset()
  } else {
    throw new Error(response.message || '提交失败，未知错误')
  }
}

// 重置表单
const handleReset = () => {
  selectedItems.value = []
}
</script>

<style scoped>
.check-apply-container {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20px;
}

.el-divider {
  margin: 20px 0;
}

.fee-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: right;
}

.fee-item {
  margin-bottom: 10px;
  font-size: 14px;
}

.fee-item.total {
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.fee-value {
  display: inline-block;
  width: 100px;
  text-align: right;
}

.payment-content {
  padding: 10px;
}

.payment-info {
  margin-bottom: 20px;
  line-height: 1.8;
}

.payment-info p {
  margin: 5px 0;
}

.payment-methods {
  margin-top: 20px;
}

.payment-methods h4 {
  margin-bottom: 10px;
}
</style>